import axios from "axios";
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

import { REQUEST, STORAGE_KEY } from './constants'
import { responseCode } from '@/utils/config'
import { getToken, removeUserInfo } from '@/utils/storage.ts'
import { ElLoading } from 'element-plus'
import { ref } from 'vue'
import element from '@/utils/element'
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: REQUEST.TIMEOUT
})

const loading = ref()
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'



const logoff = () => {
    // 清除 token 并跳转到登录页
   element.confirm('登录失效，请重新登录。', 'warning', '提示').then(() => {
        removeUserInfo()
        window.location.href = window.location.href.split('#')[0]
    })
    // message.error('登录失效，请重新登录。', 2, () => {
    //     removeUserInfo()
    //     window.location.href = window.location.href.split('#')[0]
    // })
}

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 在请求发送之前做一些处理
        const token = getToken()
        console.log(token,'tokentoken');
        
        const requestBody = config.data || {}
        if (token) {
            // config.headers.Authorization = `Bearer ${token}`
            config.headers.token = `${token}`
        }
        if (requestBody.ignoreLoading) {
            // 不加载loading
        } else {
            loading.value = ElLoading.service({
                lock: true,
                text: '加载中',
                background: 'rgba(0, 0, 0, 0.1)'
            })
        }
        return config
    },
    (error) => {
        // 处理请求错误
        console.error('Request error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data
        if (loading.value && loading.value.close) {
            loading.value.close()
        }

        // 如果返回的状态码不是 200，说明接口请求有误
        let params = {};
        if (response.config.data) {
          try {
            params = JSON.parse(response.config.data);
          } catch (e) {
            console.error('Failed to parse config data:', e);
          }
        }
        if (params.responseType === 'blob') {
            const contentDisposition = response.headers['content-disposition']
            console.log('contentDisposition', contentDisposition)
            return {
                data: res,
                contentType: response.headers['content-type'],
                name: response.headers['filename'] ? decodeURI(response.headers['filename']) : ''
            }
        }
        switch (res.code) {
            case REQUEST.SUCCESS_CODE:
                return res
                break
            case REQUEST.UNAUTHORIZED_CODE:
                logoff() // 退出登录
                return res
                break
            default:
                element.toast(res.desc || '请求失败', 'error')   
                Promise.reject(new Error(res.desc || '请求失败这里'))
        }
        return res
    },
    (error) => {
        if (loading.value && loading.value.close) {
            loading.value.close()
        }
        switch (error.status) {
            case responseCode.UNAUTHORIZED:
                logoff() // 退出登录
                break
            default:
                element.toast(error.message || '请求失败', 'error')
        }
        return Promise.reject(error)
    }
)

// 封装 GET 请求
export function get<T>(url: string, params?: any): Promise<T> {
    return service.get(url, { params })
}

// 封装 POST 请求
export function post<T>(url: string, data?: any): Promise<T> {
    return service.post(url, data)
}

// 封装 PUT 请求
export function put<T>(url: string, data?: any): Promise<T> {
    return service.put(url, data)
}

// 封装 DELETE 请求
export function del<T>(url: string, params?: any): Promise<T> {
    return service.delete(url, { params })
}

export default service


